<template>
  <div class="menu-container">
    <el-card class="table-card">
      <template #header>
        <el-button type="primary" @click="handleAdd">新增菜单</el-button>
      </template>

      <!-- 菜单表格 -->
      <el-table
        :data="menuList"
        row-key="id"
        border
        :tree-props="{ children: 'children' }"
        v-loading="loading"
      >
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="code" label="菜单编码" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            {{ scope.row.type === 1 ? '目录' : '菜单' }}
          </template>
        </el-table-column>
        <el-table-column label="图标" width="70" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="20">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleAdd(scope.row)">添加子菜单</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      @close="handleDialogClose"
    >
      <el-form 
        ref="menuFormRef"
        :model="menuForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuOptions"
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择上级菜单"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称"/>
        </el-form-item>
        <el-form-item label="菜单编码" prop="code">
          <el-input v-model="menuForm.code" placeholder="请输入菜单编码"/>
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :value="1" label="目录">目录</el-radio>
            <el-radio :value="2" label="菜单">菜单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select 
            v-model="menuForm.icon" 
            placeholder="请选择图标"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="(icon, name) in ElementPlusIconsVue"
              :key="name"
              :label="name"
              :value="name"
            >
              <el-icon>
                <component :is="name" />
              </el-icon>
              <span style="margin-left: 8px">{{ name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 数据列表
const menuList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add/edit
const dialogTitle = ref('新增菜单')

// 表单相关
const menuFormRef = ref(null)
const menuForm = ref({
  parentId: 0,
  name: '',
  code: '',
  type: 1,
  icon: '',
  path: '',
  sort: 0
})

const rules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  icon: [{ required: true, message: '请选择图标', trigger: 'change' }]
}

const menuOptions = ref([])

// 初始化表单数据
const initForm = () => {
  menuForm.value = {
    parentId: 0,
    name: '',
    code: '',
    type: 1,
    icon: '',
    path: '',
    sort: 0
  }
}

// 获取菜单树形数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request('/api/menu/tree')
    if (res.code === 200) {
      menuList.value = res.data
      menuOptions.value = [{ id: 0, name: '顶级菜单' }, ...res.data]
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 新增菜单
const handleAdd = (row) => {
  dialogType.value = 'add'
  dialogTitle.value = row ? '新增子菜单' : '新增菜单'
  initForm()
  if (row) {
    menuForm.value.parentId = row.id
  }
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = async (row) => {
  try {
    // 获取最新的菜单数据
    const res = await request(`/api/menu/get?id=${row.id}`, {
      method: 'GET'
    })
    
    if (res.code === 200) {
      // 先设置对话框状态
      dialogType.value = 'edit'
      dialogTitle.value = '编辑菜单'
      
      // 再设置表单数据
      menuForm.value = {
        id: res.data.id,
        parentId: res.data.parentId || 0,
        name: res.data.name,
        code: res.data.code,
        type: res.data.type,
        icon: res.data.icon || '',
        path: res.data.path || '',
        sort: res.data.sort || 0
      }
      
      // 最后显示对话框
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取菜单详情失败:', error)
    ElMessage.error('获取菜单详情失败')
  }
}

// 删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request(`/api/menu/${row.id}`, {
        method: 'DELETE'
      })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除菜单失败:', error)
    }
  })
}

// 对话框关闭时重置表单
const handleDialogClose = () => {
  initForm()
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!menuFormRef.value) return
  
  try {
    // 表单验证
    await menuFormRef.value.validate()
    
    const url = dialogType.value === 'add' ? '/api/menu/add' : '/api/menu/update'
    const method = 'POST'  // 统一使用 POST 方法
    
    const res = await request(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(menuForm.value)
    })
    
    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 初始化
onMounted(() => {
  initForm()
  getList()
})
</script>

<style scoped>
.menu-container {
  padding: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.el-select-dropdown__item {
  display: flex;
  align-items: center;
}
</style> 